home *** CD-ROM | disk | FTP | other *** search
- %
- % "polish.t" performs reverse polish arithmetic
- %
- % Sample program for the T Interpreter by:
- %
- % Stephen R. Schmitt
- % 962 Depot Road
- % Boxborough, MA 01719
- %
-
- var R : array[64] of real % stack
-
- var expn : string % for keyboard input
- var i, len, n : int % global values
-
- program
-
- var ch : string
-
- prompt "enter an RPN expression:"
- get expn : *
- put "expn: ",expn
-
- expn := expn & " " % must terminate line with space
- len := length( expn )
-
- i := -1
- n := 0
- R[n] := 0.0 % push zero for unary operations
-
- loop
-
- i := i + 1
- exit when i >= len % at end of line
-
- continue when expn[i] = ' ' % skip white spaces
-
- ch[0] := expn[i] % for use in index
- ch[1] := chr( 0 )
-
- if index( "0123456789", ch ) >= 0 then
-
- get_number
-
- elsif expn[i] = '+' then % add and pop stack
-
- if n < 1 then
-
- put "error"
-
- else
-
- R[n-1] := R[n-1] + R[n]
- n := n - 1
-
- end if
-
- elsif expn[i] = '-' then % subtract and pop stack
-
- if n < 1 then
-
- put "error"
-
- else
-
- R[n-1] := R[n-1] - R[n]
- n := n - 1
-
- end if
-
- elsif expn[i] = '*' then % multiply and pop stack
-
- if n < 1 then
-
- put "error"
-
- else
-
- R[n-1] := R[n-1] * R[n]
- n := n - 1
-
- end if
-
- elsif expn[i] = '/' then % divide and pop stack
-
- if n < 1 then
-
- put "error"
-
- else
-
- R[n-1] := R[n-1] / R[n]
- n := n - 1
-
- end if
-
- else
-
- exit
-
- end if
-
- end loop
-
- put "result: ", R[n] % end of main program
-
- end program
-
- procedure get_number
-
- var ch : string
- var j : int := 0 % start of number string
- var number : string % buffer for conversion
-
- i := i - 1
- loop % get integer part
-
- i := i + 1
- ch[0] := expn[i] % for use in index
- ch[1] := chr( 0 )
- number[j] := expn[i]
- j := j + 1
-
- continue when index( "0123456789", ch ) >= 0
-
- if expn[i] = '.' then
-
- loop % get fractional part
-
- i := i + 1
- ch[0] := expn[i] % for use in index
- ch[1] := chr( 0 )
- number[j] := expn[i]
- j := j + 1
-
- continue when index( "0123456789", ch ) >= 0
-
- exit
-
- end loop
-
- end if
-
- number[j] := chr( 0 ) % null terminate string
-
- exit
-
- end loop
-
- n := n + 1 % push number onto stack
- R[n] := strreal( number )
-
- end procedure